﻿using System;
using System.Diagnostics;
using System.Threading;
using Hydra.Core;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

namespace Hydra.Cockpit
{
    class Program
    {
        // Create a logger for use in this class
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        static void Main(string[] args)
        {
            // error handling
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;

            // test if I'm running as 64bit process
            log.InfoFormat("Hydra console launched, 64bit={0}", Environment.Is64BitProcess);

            // launch notepad
            var pid = Process.Start("notepad").Id;
            log.InfoFormat("Launch notepad, pid={0}", pid);
            log.Info("Press enter to continue...");
            Console.ReadLine();

            // inject core-x86/x64.dll into target process
            var doctor = Hospital.FindDoctor();
            doctor.Inject(pid);
            log.Info("notepad was injected successfully");

            // hook shell32!ShellAboutW
            Thread.Sleep(2000);
            doctor.ApplyDetours(Detours.CreateFakeAssembly());
            log.Info("Apply detours successfully");
            log.Info("Press enter to continue...");
            Console.ReadLine();
            doctor.ReleaseDetours();

            // exit when hit enter
            log.Info("Press enter to exit...");
            Console.ReadLine();

            // cleanup
            doctor.Uninject();
            log.Info("notepad was uninjected successfully");
        }

        private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var error = e.ExceptionObject as Exception;
            if (error != null)
            {
                log.Fatal("OnUnhandledException", error);
            }
            else
            {
                log.Fatal("OnUnhandledException");
            }
        }
    }
}
